import cv2 as cv
import numpy as np

# ----------------------------视频目标追踪-------------------------

cap = cv.VideoCapture('car.mp4')

# ret, frame = cap.read() #获取视频的第一帧图片
# cv.imshow('frame', frame) 
# cv.waitKey(0)
# cv.destroyAllWindows()

ret, frame = cap.read() #获取视频的第一帧图片
# 行，高，列，宽
r, h, c, w = 200, 80, 0, 100  #识别的是那座山峰
track_window = (c, r, w, h) 

roi = frame[r:r+h, c:c+w] #指定感兴趣区域
hsv_roi = cv.cvtColor(roi, cv.COLOR_BGR2HSV) #转换为HSV色彩空间

# 计算直方图
roi_hist = cv.calcHist([hsv_roi], [0], None, [180], [0, 180])
# 归一化
cv.normalize(roi_hist, 0, 255, cv.NORM_MINMAX)

# 目标追踪

# 设置终止条件
term_criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 1) # 终止条件，最大迭代次数为10，精度为1

# 处理每一帧
while True:

    ret, frame = cap.read() #获取当前帧

    if ret == True:
        hsv = cv.cvtColor(frame, cv.COLOR_BGR2HSV) #转换为HSV色彩空间
        dst = cv.calcBackProject([hsv], [0], roi_hist, [0, 180], 1) #计算直方图的反向投影

        ret, track_window = cv.meanShift(dst, track_window, term_criteria) #进行meanshift目标追踪

        x, y, w, h = track_window #获取目标的坐标和大小
        img2 = cv.rectangle(frame, (x, y), (x+w, y+h), 255, 2) #画出目标的矩形框
        cv.imshow('img2', img2) #显示图像

        if cv.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

cap.release()
cv.destroyAllWindows()